package org.openbpm.form.rest.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.rest.BaseController;
import org.openbpm.base.rest.ControllerTools;
import org.openbpm.form.model.FormCustDashboard;
import org.openbpm.form.model.custsql.FormCustSql;
import org.openbpm.form.service.FormCustDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({"/form/formCustDashboard/"})
public class FormCustDashboardController extends BaseController<FormCustDashboard> {

    @Autowired
    private FormCustDashboardService formCustDashboardService;

    //get,getByCode,saveData,remove,listJson

    @RequestMapping({"/getByCode"})
    @CatchErr
    public ResultMsg<FormCustDashboard> getByCode(@RequestParam String code) throws Exception {
        if (StringUtil.isEmpty(code)) {
            return ResultMsg.ERROR("ID不能为空");
        }
        FormCustDashboard formCustDashboard = formCustDashboardService.getOne(new QueryWrapper<FormCustDashboard>().lambda().eq(FormCustDashboard::getCode, code));
        // 计算权限 chart.hasPermission
        if(formCustDashboard!=null && formCustDashboard.getCharts()!=null){
            JSONArray jsonArray = JSONUtil.parseArray(formCustDashboard.getCharts());
            for(int i=0; i<jsonArray.size(); i++){
                JSONObject chartJson = jsonArray.getJSONObject(i);
                // TODO permission
                chartJson.set("hasPermission","1");
            }
            formCustDashboard.setCharts(JSONUtil.toJsonStr(jsonArray));
        }
        return formCustDashboard == null ? ResultMsg.ERROR("自定义列表不存在,code:" + code) : ResultMsg.SUCCESS(formCustDashboard);
    }

    @RequestMapping({"/saveData"})
    @CatchErr
    public ResultMsg<String> saveData(@RequestBody FormCustDashboard formCustDashboard) throws Exception {
        return super.save(formCustDashboard);
    }

    @Override
    protected String getModelDesc() {
        return "Cust Dashboard";
    }
}
